package com.icetech.eom.service.ws.cust;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.icetech.commonbase.JsonTools;
import com.icetech.eom.domain.request.DeviceRequest;
import com.icetech.eom.domain.response.DeviceBaseResponse;
import com.icetech.eom.domain.response.DeviceResponse;
import com.icetech.eom.domain.response.WebServiceResponse;
import com.icetech.eom.domain.sys.User;
import com.icetech.eom.domain.tx.Device;
import com.icetech.eom.domain.tx.UDev;
import com.icetech.eom.domain.tx.dto.UserDeviceDto;
import com.icetech.eom.service.tx.IDeviceService;
import com.icetech.eom.service.tx.IUDevService;
import com.icetech.eom.service.tx.IUserService;
import com.icetech.eom.common.utils.RedisTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 设备服务接口 实现类
 * @author wangzw
 */
@Slf4j
@Component
public class SpringDeviceServer {

    @Autowired
    private RedisTokenUtil redisTokenUtil;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IUDevService iuDevService;
    @Autowired
    private IUserService userService;

    @Transactional(rollbackFor = Exception.class)
    public String getDeviceList(String para) {
        log.info("<获取设备列表> 参数:{}",para);
        DeviceBaseResponse webServiceResponse = new DeviceBaseResponse();
        DeviceRequest deviceRequest = JsonTools.toBean(para, DeviceRequest.class);
        //验证token的有效性
        boolean expiration = redisTokenUtil.isExpiration(deviceRequest.getToken());
        if (expiration){
            //token 失效
            webServiceResponse.setState(2+"");
            webServiceResponse.setRetmsg("非法用户");
            return JsonTools.toString(webServiceResponse);
        }
        String searchKey = StringUtils.isEmpty(deviceRequest.getPara())?"":deviceRequest.getPara();
        String curpage = StringUtils.isEmpty(deviceRequest.getCurpage())?"0":deviceRequest.getCurpage();
        String pageSize = StringUtils.isEmpty(deviceRequest.getPagenum())?"20":deviceRequest.getPagenum();
        String userid = deviceRequest.getUserid();
        PageInfo<Device> devicePageInfo = deviceService.selectByUserIdPage(searchKey, Integer.valueOf(curpage),Integer.valueOf(pageSize), Long.valueOf(userid));
        List<Device> devices = devicePageInfo.getList();
        List<DeviceResponse> deviceResponses = Lists.newArrayList();
        for (Device device : devices) {
            DeviceResponse deviceResponse = new DeviceResponse();
            deviceResponse.setDevid(device.getId()+"");
            deviceResponse.setDevname(device.getDevName());
            deviceResponse.setGuid(device.getGuid());
            deviceResponse.setPosition(device.getPosition());
            deviceResponses.add(deviceResponse);
        }
        webServiceResponse.setRetmsg("");
        webServiceResponse.setState(0+"");
        webServiceResponse.setData(deviceResponses);
        webServiceResponse.setTotal((int) devicePageInfo.getTotal());
        webServiceResponse.setTotalPage(devicePageInfo.getPages());
        return JsonTools.toString(webServiceResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    public String bindDevice(String para) throws JSONException {
        log.info("<绑定设备> 参数:{}",para);
        WebServiceResponse webServiceResponse = new WebServiceResponse();
        JSONObject jsonObject = new JSONObject(para);
        String token = jsonObject.get("token").toString();
        String guid = jsonObject.get("guid").toString();
        String userid =jsonObject.get("userid").toString();
        String devname =jsonObject.get("devname").toString();
        String passwd =jsonObject.get("passwd").toString();
        boolean expiration = redisTokenUtil.isExpiration(token);
        if (expiration){
            //token 失效
            webServiceResponse.setState(2+"");
            webServiceResponse.setRetmsg("非法用户");
            return JsonTools.toString(webServiceResponse);
        }

        Device device = deviceService.findByUid(guid);
        if (Objects.isNull(device) || !device.getIsEnabled() || !passwd.equals(device.getPasswd())){
            webServiceResponse.setState(3+"");
            webServiceResponse.setRetmsg("非法设备");
            return JsonTools.toString(webServiceResponse);
        }

        //查看当前绑定是否存在
        UDev uDev = iuDevService.selectByUserIdAndDevId(device.getId(),Long.valueOf(userid));
        if (Objects.nonNull(uDev)){
            webServiceResponse.setState(3+"");
            webServiceResponse.setRetmsg("该设备已绑定,不能再绑定！");
            return JsonTools.toString(webServiceResponse);
        }

        List<UserDeviceDto> userDeviceDtos = iuDevService.selectBindRegister(device.getId());
        if (!device.getDevType() && !CollectionUtils.isEmpty(userDeviceDtos)){
            webServiceResponse.setState(3+"");
            webServiceResponse.setRetmsg("该设备已绑定,不能再绑定！");
            return JsonTools.toString(webServiceResponse);
        }

        //添加设备绑定信息
        UDev newUdev = new UDev();
        newUdev.setUserId(Long.valueOf(userid));
        newUdev.setDevId(device.getId());
        newUdev.setBindTime(new Date());
        iuDevService.save(newUdev);
        //更新最后一次绑定人信息
        device.setBindUserId(Long.valueOf(userid));
        device.setDevName(devname);
        deviceService.updateById(device);

        webServiceResponse.setState(0+"");
        webServiceResponse.setRetmsg("OK");
        return JsonTools.toString(webServiceResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    public String unBindDevice(String para) throws JSONException {
        log.info("<解除绑定> 参数:{}",para);
        WebServiceResponse webServiceResponse = new WebServiceResponse();
        JSONObject jsonObject = new JSONObject(para);
        String token = jsonObject.get("token").toString();
        //验证token的有效性
        boolean expiration = redisTokenUtil.isExpiration(token);
        if (expiration){
            //token 失效
            webServiceResponse.setState(2+"");
            webServiceResponse.setRetmsg("非法用户");
            return JsonTools.toString(webServiceResponse);
        }

        String devid  = (String) jsonObject.get("devid");
        String userid = (String) jsonObject.get("userid");
        //获取设备的信息
        Device device = deviceService.getById(Long.valueOf(devid));
        iuDevService.cancelBind(device.getId(), Long.valueOf(userid));
        webServiceResponse.setState(0+"");
        webServiceResponse.setRetmsg("OK");
        return JsonTools.toString(webServiceResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    public String updateDevice(String para) throws JSONException {
        log.info("<更新设备> 参数:{}",para);
        WebServiceResponse webServiceResponse = new WebServiceResponse();
        JSONObject jsonObject = new JSONObject(para);
        String token = jsonObject.get("token").toString();
        String devname = jsonObject.get("devname").toString();
        String devid = (String) jsonObject.get("devid");
        String uname = jsonObject.get("uname").toString();
        //验证token的有效性
        boolean expiration = redisTokenUtil.isExpiration(token);
        if (expiration){
            //token 失效
            webServiceResponse.setState(2+"");
            webServiceResponse.setRetmsg("非法用户");
            return JsonTools.toString(webServiceResponse);
        }
        //更新设备信息
        Device device = new Device();
        device.setId(Long.valueOf(devid));
        device.setDevName(devname);
        device.setModifier(uname);
        deviceService.updateById(device);
        webServiceResponse.setState(0+"");
        webServiceResponse.setRetmsg("OK");
        return JsonTools.toString(webServiceResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    public String checkDevice(String para) throws JSONException {
        log.info("<验证设备合法性> 参数:{}",para);
        WebServiceResponse webServiceResponse = new WebServiceResponse();
        JSONObject jsonObject = new JSONObject(para);
        String guid = jsonObject.get("guid").toString();
        String username = jsonObject.get("username").toString();
        User user = userService.findDeveloperByName(username);
        if (Objects.isNull(user)){
            webServiceResponse.setState(2+"");
            webServiceResponse.setRetmsg("非法开发者");
            return JsonTools.toString(webServiceResponse);
        }
        //获取设备信息
        Device device = deviceService.findByUid(guid);
        if (Objects.isNull(device) || !device.getIsEnabled()){
            webServiceResponse.setState(1+"");
            webServiceResponse.setRetmsg("非合法绑定设备");
            return JsonTools.toString(webServiceResponse);
        }
        UDev uDev = iuDevService.selectByUserIdAndDevId(device.getId(),user.getId());
        if (Objects.isNull(uDev)){
            webServiceResponse.setState(1+"");
            webServiceResponse.setRetmsg("非合法绑定设备");
            return JsonTools.toString(webServiceResponse);
        }
        webServiceResponse.setState(0+"");
        webServiceResponse.setRetmsg("检验成功");
        return JsonTools.toString(webServiceResponse);
    }
}
